import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Jiange
 * @create 2021-07-16-10:14
 */
public class LockAwait {
    public static void main(String[] args) {
        Share1 share = new Share1();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share.desc();
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        },"CC").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share.desc();
            }
        },"DD").start();
    }
}

class Share1{
    private int number = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void incr(){
        lock.lock();
        try{
            while(number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"---"+number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void desc(){
        lock.lock();
        try{
            while (number != 1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"---"+number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
